<?php
defined ( '_JEXEC' ) or die ( 'Restricted access' );
jimport ( 'joomla.event.plugin' );
jimport ( 'joomla.user.helper' );

class plgSystemPlg_Jarpxnow extends JPlugin {
	
	var $_plgCode = "#{jarpxnow(.*?)}#i";
	var $_plgCodeHolder = "{RPX-HOLDER-%d}";
	var $_plgCodeModifier = "#{jarpxnow(.*?)}#e";
	var $_plgCodeMakeHolder = "'{RPX-HOLDER-' . plgSystemPlg_Jarpxnow::getCount() . '}'";
	
	function plgSystemPlg_Jarpxnow(&$subject, $config) {
		parent::__construct ( $subject, $config );
		$this->plugin = &JPluginHelper::getPlugin ( 'system', 'plg_jarpxnow' );
		$this->plgParams = new JParameter ($this->plugin->params );
		
		/* Load Language file */
		$this->loadLanguage ('plg_'.$this->plugin->type.'_'.$this->plugin->name, JPATH_ADMINISTRATOR);		
	}
	
	function onAfterInitialise() {
	
		if (!file_exists(JPATH_SITE.DS.'plugins'.DS.'system'.DS.'plg_jarpxnow'.DS.'install.complete'))
		{
			$db =& JFactory ::getDBO();
			$query = "CREATE TABLE `#__jarpx_mapid` (`user_id` INT NOT NULL ,`rpxid` VARCHAR(50) NOT NULL);";
			$db->setQuery($query);
			$db->query();
			@file_put_contents('plugins/system/plg_jarpxnow/install.complete', date('r'));
		}
		
		//get token return from RPX service 
		$returntoken = (JRequest::getVar ( "auth_token", "" ) != "") ? JRequest::getVar ( "auth_token", "" ) : JRequest::getVar ( "token", "" );
		
		if ($returntoken !== "") {
			//get apikey
			$apiKey = $this->params->get( "apikey" );
			$data_post = array ('token' => $returntoken, 'apiKey' => $apiKey, 'format' => 'json' );
			//get user login info
			$authinfo = $this->get_Authinfo ( $data_post, $this->params->get ( "usecurl" ) );
			
			if ($authinfo ['stat'] == "ok") {
				$db = & JFactory::getDBO ();
				$rpxid = 'rpx' . md5 ( $authinfo ['profile'] ['identifier'] );
				$query = "SELECT user_id FROM #__jarpx_mapid WHERE rpxid='" . $rpxid . "'";
				$db->setQuery($query );
				$userid = $db->loadResult ();
				$createuser = true;
				
				if (isset($userid)) {
					
					$query = "SELECT id FROM #__users WHERE id='" . $userid . "'";
				    $db->setQuery ( $query );
				    $uid = $db->loadResult();
				    
					if ($uid == $userid) {
						//Get parameters
						$userparam = new JParameter("");
						foreach($authinfo['profile'] as $keyu => $valueu){
		                     if(is_array($valueu)){
		                     	foreach($valueu as $keyu1 => $valueu1){
		                     		$userparam->set($keyu1,$valueu1);
		                     	} 
		                     }else{
		                     	$userparam->set($keyu,$valueu);
		                     }                					
						}
						$user = new JUser($uid);	
						$user->set("_params",$userparam);					
						$user->save();
						$createuser = false;
						$username = $user->get ( "username" );
					} else {
						
						$query = "DELETE FROM #__jarpx_mapid WHERE user_id='" . $userid . "'";
						$db->setQuery ( $query );
						$db->query();
						
					}
				}
				
				//if create new user
				if ($createuser) {
					
					$register_details = array ();
					isset ( $authinfo ['profile'] ['displayName'] ) ? ($displayName = $authinfo ['profile'] ['displayName']) : ($displayName = $authinfo ['profile'] ['name'] ['displayName']);
					isset ( $authinfo ['profile'] ['preferredUsername'] ) ? ($preferredUsername = $authinfo ['profile'] ['preferredUsername']) : ($preferredUsername = $authinfo ['profile'] ['name'] ['preferredUsername']);
					$usernameexits = true;
					$index = 0;
					
					$userName = $preferredUsername."_".$authinfo ['profile']['providerName'];
//					while ( $usernameexits == true ) {
//						if (JUserHelper::getUserId ( $userName ) != 0) {
//							$index ++;
//							$userName = $preferredUsername . $index;
//						} else {
//							$usernameexits = false;
//						}
//					}
					
					//get random password and user email
					//$pwd = JUserHelper::genRandomPassword ();
					$salt = JUserHelper::genRandomPassword();
                    $crypt = JUserHelper::getCryptedPassword("joomlart", $salt);
                    $pwd = $crypt.':'.$salt;
					$register_details ['password'] = $pwd;
					
					if (isset ( $authinfo ['profile'] ['email'] )) {
						$register_details ['email'] = $authinfo ['profile'] ['email'];
					} else if (isset ( $auth_info ['profile'] ['name'] ['email'] )) {
						$register_details ['email'] = $authinfo ['profile'] ['name'] ['email'];
					} else {
					    $uri = JFactory::getURI ();
					    $domain = substr ($uri->getHost(), 4 );
						$register_details ['email'] = str_replace ( " ", "_", $userName ) . "@" . $domain;
					}
					
					$register_details ['name'] = $displayName;
					$register_details ['username'] = $userName;
					
					//Get parameters
					$userparam = new JParameter("");
					foreach($authinfo['profile'] as $keyu => $valueu){
	                     if(is_array($valueu)){
	                     	foreach($valueu as $keyu1 => $valueu1){
	                     		$userparam->set($keyu1,$valueu1);
	                     	} 
	                     }else{
	                     	$userparam->set($keyu,$valueu);
	                     }                					
					}
					
					$register_details['params'] = $userparam;
					$username = $userName;
					 
					//resgister new user
					if ($this->params->get ( "register" )) {
						
						if ($newuserid = $this->register_joomla($register_details, $authinfo )) {
							$query = "INSERT INTO #__jarpx_mapid (user_id, rpxid) VALUES ('" . $newuserid . "','" . $rpxid . "')";
							$db->setQuery ( $query );
							if (! $db->query ()) {
								JERROR::raiseError ( 500, $db->stderr () );
							}
						}
					
					}
				
				}
				//login as a user of joomla
				$this->login_joomla ( $username );
			}
		}else{
			// stay on the same page
	        if(!(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')))	
	        {  
	          $uri = JFactory::getURI();
			  $url = $uri->toString(array('path', 'query', 'fragment')); 
			  $ses =&JFactory::getSession();
			  $ses->set("afterlogin",$url);
		    }
		}
	}
	
	function onAfterRender() {
		global $mainframe;
		global $option;
		jimport ( "joomla.application.module.helper" );
		
		if ($mainframe->isAdmin ()) {
			return;
		}
		
		$body = JResponse::getBody ();
		if (! preg_match ( $this->_plgCode, $body )) {
			return;
		}
		$this->_aUSetting = $this->getUserSetting ( $body );
		if (count ( $this->_aUSetting ) > 0) {
			foreach ($this->_aUSetting as $id => $sSetting ) {
				$pgparams = $this->parseParams ( $sSetting );
				    $layout = "default";
				if(isset($pgparams) and is_array($pgparams)){     
				    foreach ( $pgparams as $pa => $val ) {
								$this->params->set ( $pa, $val );
					}
				}		
				$output = $this->loadLayout ( $this->plugin, $layout );
				$holder = sprintf ( $this->_plgCodeHolder, $id );
				$body = str_replace ( $holder, $output, $body );
			}
		}
		JResponse::setBody ( $body );
	
	}
	
	function getCount($reset = false) {
		static $count = 0;
		if ($reset)
			$count = - 1;
		return $count ++;
	}
	
	function getUserSetting(&$text) {
		if (preg_match_all ( $this->_plgCode, $text, $matches )) {
			$text = preg_replace ( $this->_plgCodeModifier, $this->_plgCodeMakeHolder, $text, - 1, $count );
			return $matches [1];
		} else {
			return array ();
		}
	
	}
	
	function getLayoutPath($plugin, $layout = 'default') {
		global $mainframe;
		
		// Build the template and base path for the layout
		$tPath = JPATH_BASE . DS . 'templates' . DS . $mainframe->getTemplate () . DS . 'html' . DS . $plugin->name . DS . $layout . '.php';
		$bPath = JPATH_BASE . DS . 'plugins' . DS . $plugin->type . DS . $plugin->name . DS . 'tmpl' . DS . $layout . '.php';
		// If the template has a layout override use it
		if (file_exists ( $tPath )) {
			return $tPath;
		} elseif (file_exists ( $bPath )) {
			return $bPath;
		}
		return '';
	}
	
	function loadLayout($plugin, $layout = 'default') {
		$layout_path = $this->getLayoutPath ( $plugin, $layout );
		if ($layout_path) {
			ob_start ();
			require $layout_path;
			$content = ob_get_contents ();
			ob_end_clean ();
			return $content;
		}
		return '';
	}
	
	function parseParams($string) {
		$string = html_entity_decode ( $string, ENT_QUOTES );
		$regex = "/\s*([^=\s]+)\s*=\s*('([^']*)'|\"([^\"]*)\"|([^\s]*))/";
		$params = null;
		if (preg_match_all ( $regex, $string, $matches )) {
			for($i = 0; $i < count ( $matches [1] ); $i ++) {
				$key = $matches [1] [$i];
				$value = $matches [3] [$i] ? $matches [3] [$i] : ($matches [4] [$i] ? $matches [4] [$i] : $matches [5] [$i]);
				$params [$key] = $value;
			}
		}
		return $params;
	}
	
    function get_Authinfo($datapost, $iscurl) {
		
		if ($iscurl && function_exists('curl_init')) {
			$curl = curl_init ();
			curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
			curl_setopt ( $curl, CURLOPT_URL, 'https://rpxnow.com/api/v2/auth_info/?token=' . $datapost ['token'] . '&&apiKey=' . $datapost ['apiKey'] . '&&format=json' );
			curl_setopt ( $curl, CURLOPT_POST, true );
			curl_setopt ( $curl, CURLOPT_POSTFIELDS, $datapost );
			curl_setopt ( $curl, CURLOPT_HEADER, false );
			curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER, false );
			$raw_json =   curl_exec ( $curl );
			curl_close ( $curl );
			
		} else if(ini_get ( 'allow_url_fopen' ) && extension_loaded("openssl")){
	        $host = "rpxnow.com";
            $path = "/api/v2/auth_info/";
            $req = "&token=".$datapost['token']."&apiKey=".$datapost['apiKey']."&format=json"; 
            $raw_json = @file_get_contents ( "https://rpxnow.com/api/v2/auth_info/?token=" . $datapost ['token'] . "&&apiKey=" . $datapost ['apiKey'] . "&&format=json" ); 			
			
		} else {
			JError::raiseWarning ( 1, JText::_ ( 'Sorry, but your server does not currently support curl  or openssl extension to use Jarpxnow plugin. Please contact your hosting manager for help' ).'.' );
			return;
		}
		
		//parse the json response into an associative array
		if(function_exists("json_decode")){			
			$authinfo = json_decode ( $raw_json, true );
		}else{				
			require_once (JPATH_ROOT . "/plugins/system/plg_jarpxnow/JSON.php");
			$json     = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
			$authinfo = $json->decode ( $raw_json );										
		}
		
		return $authinfo;
	}
	
	function register_joomla($register_details, $user_details) {
		$db = & JFactory::getDBO ();
		global $mainframe;	
		// Get required system objects
		$user 		= new JUser();
		$authorize	=& JFactory::getACL();
		
		// If user registration is not allowed, show 403 not authorized.
		$usersConfig = &JComponentHelper::getParams( 'com_users' );
 	    // Initialize new usertype setting
		$newUsertype = $usersConfig->get( 'new_usertype' );
		if (!$newUsertype) {
			$newUsertype = 'Registered';
		}
		// Set some initial user values
		$user->set('id', 0);
		$user->set('usertype', '');
		$user->set('gid', $authorize->get_group_id( '', $newUsertype, 'ARO' ));
		$date =& JFactory::getDate();
		$user->set('registerDate', $date->toMySQL());
		$user->set('name',($register_details ['name'] ? $register_details ['name'] : $register_details ['username']));
		$user->set('username',$register_details ['username']);
		$user->set('email',$register_details ['email']);
	    $user->set('password',$register_details ['password']);
	    $user->set('password2',$register_details ['password']);
	    $user->set('_params',$register_details ['params']);
	    $user->set ('block', '0' );
		$user->set ('activation', '' );
		
	    // If there was an error with registration, set the message and display form
		if ( !$user->save() )
		{
			JError::raiseWarning('', JText::_( $user->getError()));
			return false;
		}
		return $user->id;
	}
	
	function login_joomla($username) {		
		global $mainframe;
		//sign in an existing user
		jimport ( 'joomla.user.authentication' );
		JPluginHelper::importPlugin ( 'user' );
		$authenticate = & JAuthentication::getInstance ();
		$authenticate_response = new JAuthenticationResponse ( );
		$authenticate_response->status = JAUTHENTICATE_STATUS_SUCCESS;
		
		//we need only username to login
		$authenticate_response->username = $username;
		$results = $mainframe->triggerEvent ( 'onLoginUser', array (( array ) $authenticate_response,$option=array() ) );
		$returnURL = $this->get_ReturnURL ();
		$ses = &JFactory::getSession();
		
		if($ses->get("afterlogin") !== "" && $ses->get("afterlogin") !== null){
		// echo $ses->get("afterlogin");die();
		  $mainframe->redirect($ses->get("afterlogin"));
		  $ses->set("afterlogin","");
		}else{
		  $mainframe->redirect ( base64_decode ( $returnURL ) );	
		}
			
	}
	
	function get_ReturnURL() {
		
		if ($itemid = $this->params->get( 'logout' )) {
			
			$menu = & JSite::getMenu ();
			$item = $menu->getItem ( $itemid );
			$url = JRoute::_ ( $item->link . '&Itemid=' . $itemid, false );
		} else {
			$uri = JFactory::getURI ();
			$url = $uri->current ();
			$url .= '?';
			$paramarray = $uri->getQuery ( true );
		
			foreach ( $paramarray as $paramname => $paramvalue ) {
				if ($paramname != 'token') {
					$url .= $paramname;
					$url .= '=';
					$url .= $paramvalue;
					$url .= '&';
				}
				$url = substr(0,strrpos($url,"&"),$url);
			}
		}
		return base64_encode ( $url );
	}
	public function loadModuleParams()
	{
		 $arr_params = array();
		 $arr_params["pretext"] = $this->params->get("pretext","");
     	 $arr_params["posttext"] = $this->params->get("posttext","");
     	 $arr_params["logout"] = $this->params->get("logout","");
     	 $arr_params["greeting"] = $this->params->get("greeting",0);
     	 $arr_params["name"] = $this->params->get("name",0);
     	 $arr_params["usesecure"] = $this->params->get("usesecure",0);
     	 $content_params = "";
     	 foreach($arr_params as $key => $value)
		 {
			if(!empty($value))
			{
			   $content_params .= $key."=".$value."\n";
			}
		 }
     	 return $content_params;
	}
	
}

?>
